// 命名管道
#ifndef __COMM_HPP__
#define __COMM_HPP__
#include <iostream>
using namespace std;
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <cassert>
#define MODE 0666
#define Path "./fifo"
class Fifo
{
public:
    Fifo(const string &path)
        : _path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(), MODE);
        if (n == 0)
        {
            cout << "创建命名管道成功" << endl;
        }
        else
        {
            cerr << "创建命名管道失败,错误码:" << errno << "错误信息" << strerror(errno) << endl;
        }
    }
    ~Fifo()
    {
        // unlink既可以删除链接文件，也可以删除普通文件
        // rm指令内部调用unlink
        int n = unlink(_path.c_str());
        if (n == 0)
        {
            cout << "删除fifo file:" << _path << "成功" << endl;
        }
        else
        {
            cerr << "创建命名管道失败,错误码:" << errno << "错误信息" << strerror(errno) << endl;
        }
    }

private:
    string _path; // 路径+文件名
};
class Sync
{
public:
    Sync()
        : wfd(-1), rfd(-1)
    {
    }
    ~Sync()
    {
    }
    void OpenRead()
    {
        rfd = open(Path, O_RDONLY);
    }
    void OpenWrite()
    {
        wfd = open(Path, O_WRONLY);
    }
    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(rfd, &c, sizeof(uint32_t));
        if (n == sizeof(uint32_t))
        {
            cout << "等待结束，被唤醒" << endl;
        }
        else if (n == 0)
        {
            ret = false;
        }
        else
        {
            ret = false;
        }
        return false;
    }
    void WaitUp()
    {
        uint32_t c = 0;
        ssize_t n = write(wfd, &c, sizeof(uint32_t));
        assert(n == sizeof(uint32_t));
        cout << "写入完成,唤醒读取端" << endl;
    }

private:
    int wfd;
    int rfd;
};
#endif